package com.lzh.others.Thread.test;

import java.util.concurrent.locks.ReentrantLock;

import static com.lzh.others.Thread.test.TestMain.ORGID_LOCKS;
import static com.lzh.others.Thread.test.TestMain.RETRY_QUEUE;

public class DataRefreshTask implements Runnable {
    private final String orgId;
    private final String key;
    private final ReentrantLock lock;

    public DataRefreshTask(String orgId, String key) {
        this.orgId = orgId;
        this.key = key;
        this.lock = ORGID_LOCKS.computeIfAbsent(orgId, k -> new ReentrantLock(true));
    }

    public boolean acquireLock() {
        return lock.tryLock();
    }

    @Override
    public void run() {
        if (acquireLock()) { // 先尝试获取锁
            try {
                System.out.println(Thread.currentThread().getName() + " 唯一key = " + key);
                Thread.sleep(2000); // 假设此处代表需要同步的业务逻辑
                // 实际业务逻辑放在这里...
            } catch (InterruptedException ignored) {
                ignored.printStackTrace();
            } finally {
                lock.unlock(); // 在业务逻辑完成后释放锁
            }
        } else {
//            System.out.println("相同区域还没有释放锁,无法获取锁,存入RETRY_QUEUE队列,orgId = " + orgId + " key = " + key);
            RETRY_QUEUE.offer(this);
        }
    }
}
